import threading
from  periphery import GPIO


class LEDController:
    LED_STATE_OFF = 0
    LED_STATE_ON = 1
    LED_STATE_BLINK = 2

    def __init__(self):
        # LED名称对应的设备名（按你实际环境调整）
        self.pins = [205,201,200,145]
        self.led_names = ['led2','led3','led4','led5']
        # 生成periphery LED对象字典
        self.led_objs = {}
        for pin in self.pins:
            self.led_objs[self.led_names[self.pins.index(pin)]] = GPIO("/dev/gpiochip0",pin, "out")  # GPIO_out

        # 各LED状态管理数据结构字典，方便每个LED独立运行
        # key=led_name, val=dict{state,计数器,定时器}
        self.led_status = {}
        for name in self.led_names:
            self.led_status[name] = {
                'state': self.LED_STATE_OFF,
                'time_on': 0,
                'time_blink': 0,
                'period_blink': 0,
                'cnt_time_on': 0,
                'cnt_time_blink': 0,
                'cnt_period_blink': 0,
                'timer': None,
            }

        self.timer_interval = 0.1  # 100ms定时周期

    # LED硬件操作
    def _led_on(self, led_name):
        led = self.led_objs[led_name]
        led.write(True)

    def _led_off(self, led_name):
        led = self.led_objs[led_name]
        led.write(False)

    def _led_toggle(self, led_name):
        led = self.led_objs[led_name]
        current_state = led.read()
        led.write(not current_state)

    # 定时器回调
    def _timer_callback(self, led_name):
        status = self.led_status[led_name]
        timer_should_restart = True  # 标志位，判断是否需要重启定时器
        if status['state'] == self.LED_STATE_ON:
            status['cnt_time_on'] += 1
            if status['cnt_time_on'] >= status['time_on']:
                self._led_off(led_name)
                status['cnt_time_on'] = 0
                self._stop_timer(led_name)
                status['state'] = self.LED_STATE_OFF
                timer_should_restart = False
                # return

        elif status['state'] == self.LED_STATE_BLINK:
              status['cnt_time_blink'] += 1
              status['cnt_period_blink'] += 1
            
              if status['cnt_period_blink'] >= status['period_blink']:
                 status['cnt_period_blink'] = 0
                 self._led_toggle(led_name)
                
              if status['cnt_time_blink'] >= status['time_blink']:
                 self._led_off(led_name)
                 status['cnt_time_blink'] = 0
                 status['cnt_period_blink'] = 0 # 重置周期计数器
                 self._stop_timer(led_name)
                 status['state'] = self.LED_STATE_OFF
                 timer_should_restart = False 
                # return
        if timer_should_restart: # 检查定时器是否仍然存在
            self._start_timer(led_name)
    # 启动定时器
    def _start_timer(self, led_name):
        status = self.led_status[led_name]
        if status['timer'] is not None:
            status['timer'].cancel() # 先取消已存在的定时器
        status['timer'] = threading.Timer(self.timer_interval, self._timer_callback,args=[led_name])  
        status['timer'].start()

    # 停止定时器
    def _stop_timer(self, led_name):
        status = self.led_status[led_name]
        if status['timer'] is not None:
            status['timer'].cancel()
            status['timer'] = None

    # 外部接口
    def led_init(self):
        # 全部关闭，初始化状态
        for led_name in self.led_names:
            # with self.led_status[led_name]['lock']:
            self._stop_timer(led_name)
            self._led_off(led_name)
            status = self.led_status[led_name]
            status['state'] = self.LED_STATE_OFF
            status['time_on'] = 0
            status['time_blink'] = 0
            status['period_blink'] = 0
            status['cnt_time_on'] = 0
            status['cnt_time_blink'] = 0
            status['cnt_period_blink'] = 0

    def led_on(self, led_name, time_sec):
        if led_name not in self.led_objs:
            raise ValueError(f"Invalid LED name {led_name}")

        # with self.led_status[led_name]['lock']:
        self._stop_timer(led_name)
        status = self.led_status[led_name]
        status['time_on'] = int(time_sec * 10)
        status['cnt_time_on'] = 0
        self._led_on(led_name)
        status['state'] = self.LED_STATE_ON
        self._start_timer(led_name)

    def led_off(self, led_name):
        if led_name not in self.led_objs:
            raise ValueError(f"Invalid LED name {led_name}")

        # with self.led_status[led_name]['lock']:
        self._stop_timer(led_name)
        self._led_off(led_name)
        status = self.led_status[led_name]
        status['state'] = self.LED_STATE_OFF
        status['cnt_time_on'] = 0
        status['cnt_time_blink'] = 0
        status['cnt_period_blink'] = 0

    def led_blink(self, led_name, period, time_sec):
        """
        period: 闪烁周期单位为0.1秒,如5代表0.5秒切换
        time_sec: 总持续时间秒数
        """
        if led_name not in self.led_objs:
            raise ValueError(f"Invalid LED name {led_name}")

        # with self.led_status[led_name]['lock']:
        self._stop_timer(led_name)
        status = self.led_status[led_name]
        status['time_blink'] = int(time_sec * 10)
        status['period_blink'] = period
        status['cnt_time_blink'] = 0
        status['cnt_period_blink'] = 0
        self._led_on(led_name)  # 闪烁开始时，先点亮LED
        status['state'] = self.LED_STATE_BLINK
        self._start_timer(led_name)

    def close(self):
        # 关闭所有LED对象，释放文件句柄
        for name in self.led_objs:
            # with self.led_status[name]['lock']:
            self._stop_timer(name)
            self._led_off(name)
            self.led_objs[name].close()




